package com.tz.yiqingapp.upload;

import com.tz.yiqingapp.config.AccessLimit;
import com.tz.yiqingapp.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController
public class UploadController {

    @javax.annotation.Resource
    private ResourceLoader resourceLoader;

    @RequestMapping("/upload/upload")
    @AccessLimit(times = 5)
    public HashMap<String, Object> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        if (request.getSession().getAttribute("loginrole") != null &&
                (request.getSession().getAttribute("loginrole").equals("admin")
                        || request.getSession().getAttribute("loginrole").equals("teacher"))) {
            String name = "";
            try {
                String fileName = System.currentTimeMillis() + "";
                name = fileName + ".png";
                String destFileName = name;
                File destFile = new File(destFileName);
                multipartFile.transferTo(destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResponseUtils.success(name);
        } else {
            return ResponseUtils.notlogin("not login");
        }
    }

    @Autowired
    private FileService fileService;


    @GetMapping("/downloadFile/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        // Load file as Resource
        Resource resource = fileService.loadFileAsResource(fileName);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (Exception ex) {
            System.out.println("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/media";
        }
        if (resource == null)
            return null;
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

}